package com.nariano.server.services.cityservice.impl;

import java.util.List;
import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;
import javax.persistence.Query;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.jpa.JpaCallback;
import org.springframework.orm.jpa.support.JpaDaoSupport;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.nariano.server.domain.entities.Area;
import com.nariano.server.domain.entities.City;
import com.nariano.server.domain.entities.Location;
import com.nariano.server.domain.entities.User;
import com.nariano.server.services.cityservice.CityService;
import com.nariano.server.services.mapservice.MapService;

@Transactional
public class CityServiceJpa extends JpaDaoSupport implements CityService {

	@Autowired
    @Qualifier(value="mapService")
    private MapService mapService;
	
    private Logger logger = Logger.getLogger(CityServiceJpa.class.getCanonicalName());
    
    
    public List<City> getCities() {
        return getJpaTemplate().find("select c from City c");
    }
    
    public List<City> getCities(final User user) {
    	return (List<City>) getJpaTemplate().execute(new JpaCallback() {
			
			@Override
			public Object doInJpa(EntityManager em) throws PersistenceException {
				Query q = em.createQuery("select c from City c where c.ownerId=:owner");
				q.setParameter("owner", user.getId());
				return q.getResultList();
			}
		});
    }
    
    public City getCity(Location location) {
        Area area = findArea(location);
        City city = area==null ? null : area.getCity();
        logger.fine(""+ city);
        return city;
    }

    private Area findArea(Location location) {
        return mapService.getArea(location);
    }

    public List<City> findCity(String name) {
        List list = getJpaTemplate().find("select c from City c where c.name='"+name+"'");
        return list;
    }

  
	public void updateCity(City city) {
		Assert.notNull(city.getId(),"Tried to update a city that has not added to any area");
		getJpaTemplate().merge(city);
	}

}
